package com.fengwk.support.thread;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

import com.fengwk.support.util.ArrayUtils;
import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

/**
 * 死锁探测器
 * 
 * @author fengwk
 *
 */
public class DeadlockDetector implements Runnable {

	private static final Logger LOG = LoggerUtils.getLogger(DeadlockDetector.class);
	
	private final static ThreadMXBean tmxb = ManagementFactory.getThreadMXBean();

	/**
	 * 扫描间隔/毫秒
	 */
	private long scanInterval;
	
	/**
	 * 
	 * @param scanInterval 扫描间隔/毫秒
	 */
	public DeadlockDetector(long scanInterval) {
		this.scanInterval = scanInterval;
	}
	
	@Override
	public void run() {
		while (true) {
			long[] ids = tmxb.findDeadlockedThreads();
			if (ArrayUtils.isNotBlank(ids)) {
				for (Thread t: Thread.getAllStackTraces().keySet()) {
					for (long id: ids) {
						if (id == t.getId()) {
						    LOG.error(t.getName() + " interrupt");
							t.interrupt();
						}
					}
				}
			}
			try {
				Thread.sleep(scanInterval);
			} catch (Exception e) {
			    LOG.error(e);
			}
		}
	}
	
	public void start() {
		Thread t = new Thread(this);
		t.setDaemon(true);
		t.start();
	}
	
}
